package com.shanshi.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.LocationSource;
import com.ant.liao.GifView;
import com.ant.liao.GifView.GifImageType;
import com.google.gson.Gson;
import com.shanshi.activity.response.IndexInfo;
import com.shanshi.activity.service.IndexService;
import com.shanshi.activity.tool.CustomDialog;

import java.util.Date;

public class IndexImageActivity extends Activity implements LocationSource,AMapLocationListener {

	private double latitude;
	private double longitude;
	//定位需要的声明
	private AMapLocationClient mLocationClient = null;//定位发起端
	private AMapLocationClientOption mLocationOption = null;//定位参数
	private LocationSource.OnLocationChangedListener mListener = null;//定位监听器
	
	// 存储全局数据
	private	SharedPreferences sharedPreferences ;
	private static boolean dd = true;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		sharedPreferences = IndexImageActivity.this.getSharedPreferences("share", MODE_PRIVATE);
		// 执行本页的操作,显示gif图片
		showGif();
	}
	
	/**
	 * 显示gif图片
	 */
	private void showGif() {
		setContentView(R.layout.index_image);
		Log.i("aaaaa====","aaa");
		// 动态注册receiver
		IntentFilter filter = new IntentFilter("IndexService");
		filter.addCategory(Intent.CATEGORY_DEFAULT);
		MessageReceiver receiver = new MessageReceiver();
		registerReceiver(receiver, filter);
		Log.i("bbbbb====","aaa");
		/************** 显示gif ********************/
		// 从xml中得到GifView的句柄
		GifView gf1 = (GifView) findViewById(R.id.gif1);
		// 设置Gif图片源
		gf1.setGifImage(R.drawable.index_img);
		Log.i("ccccccc====","aaa");
		// 获取屏幕尺寸
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);

		// 设置显示的大小，拉伸或者压缩 （屏幕大小）
		gf1.setShowDimension(dm.widthPixels, dm.heightPixels);
		Log.i("ddddd====","aaa");
		// 设置加载方式：先加载后显示、边加载边显示、只显示第一帧再显示
		gf1.setGifImageType(GifImageType.COVER);
		Log.i("eeeee====","aaa");
		
		
		gf1.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			
			@Override
			public void onGlobalLayout() {
				// TODO Auto-generated method stub
				Log.i("gggggg====","加载完成了");
				
				// 设置定时器，定制gif显示的时间，当gif显示完毕之后，出现定位弹窗（用户体验）,默认3秒
				Log.i("oldtime====", new Date()+"");
				/*Timer timer=new Timer();//实例化Timer类   
				timer.schedule(new TimerTask(){   
				public void run(){ 
					IndexImageActivity.dd = false;
				this.cancel();}},3000);//3秒 
				boolean ee = IndexImageActivity.dd;*/
				//Log.i("ee===#####=", ee+"");
//				long aa = 123456789;
//				while (aa > 0) {
//					aa--;
//					Log.i("ee====++++", aa+"");
//					break;     //弹出
//				}
//				Log.i("newtime====", new Date()+"");
				
				// 存储全局数据
				/*SharedPreferences sharedPreferences = IndexImageActivity.this.getSharedPreferences("share", MODE_PRIVATE);

				// 是否是第一次运行app(true：第一次；)
				boolean isFirstRun = sharedPreferences.getBoolean("isFirstRun", true);

				if (isFirstRun) {
					// 改变全局变量的状态
					Editor editor = sharedPreferences.edit();
					editor.putBoolean("isFirstRun", false);
					editor.commit();
					//gps应用（判断定位以及获取定位信息）
					GPSAppliocation();
				} else {
					// 不是第一次运行，判断用户是否登录(0:未登录)
					int userId = sharedPreferences.getInt("userId", 0);

					if (userId > 0) {// 登录
						// 去首页，显示3秒的门店推广图（上一次的门店图），然后跳转到推广页
						Intent intent = new Intent();
						intent.setClass(IndexImageActivity.this, IndexActivity.class);
						startActivity(intent);
					}else{
						//gps应用（判断定位以及获取定位信息）
						GPSAppliocation();
					}
				}*/
			}
		});
		// 隐藏状态栏
		gf1.setSystemUiVisibility(View.INVISIBLE);
		initLoc();
		GPSAppliocation();
		Log.i("fffff====","aaa");
	}
	

	/*********** GPS应用 **************/
	
	 LocationListener locListener=new LocationListener(){

			@Override
			public void onLocationChanged(Location location) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub
				
			}
     	
     };
	private void GPSAppliocation() {
		//得到系统的位置服务，判断GPS是否激活
		LocationManager locationManager=(LocationManager) getSystemService(LOCATION_SERVICE);
        boolean openState = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

		if(openState){
		    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		    if(location==null){
		    	location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);  
		    }
		    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locListener);
		    //向后台请求门店信息需要用到的参数（里面的经纬度需要定位）
			Intent intentObj = new Intent(IndexImageActivity.this, IndexService.class);
			intentObj.putExtra("phoneTypeNum", getPhoneModule());	//设备号
			//存储全局变量
			Editor editor = sharedPreferences.edit();
			editor.putString("phoneTypeNum",getPhoneModule());
//			if(location!=null){
//				Log.e("Longitude",location.getLongitude()+"");
//				Log.e("Latitude",location.getLatitude()+"");
//				intentObj.putExtra("longitude", location.getLongitude());	//经度
//				intentObj.putExtra("latitude", location.getLatitude());		//纬度
//
//				editor.putString("userLongitude",location.getLongitude()+"");
//				editor.putString("userLatitude",location.getLatitude()+"");
//			}else{
//				Log.e("=====","error");
//				intentObj.putExtra("longitude", 0);	//经度
//				intentObj.putExtra("latitude", 0);		//纬度
//
//				editor.putString("userLongitude",0+"");
//				editor.putString("userLatitude",0+"");
//			}
			intentObj.putExtra("longitude", longitude);	//经度
				intentObj.putExtra("latitude", latitude);		//纬度

				editor.putString("userLongitude",longitude+"");
				editor.putString("userLatitude",latitude+"");
			editor.commit();
			startService(intentObj);
		}else{
			//打开定位弹窗
			handler.sendEmptyMessageDelayed(2, 3000);
		}
		// 定时器，定制gif显示的时间，当gif显示完毕之后，出现定位弹窗（用户体验）
		/*Timer timer = new Timer();
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				
				//得到系统的位置服务，判断GPS是否激活
				LocationManager locationManager=(LocationManager) getSystemService(LOCATION_SERVICE);
		        boolean openState = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

				if(openState){
				    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
				    //向后台请求门店信息需要用到的参数（里面的经纬度需要定位）
					Intent intentObj = new Intent(IndexImageActivity.this, IndexService.class);
					intentObj.putExtra("phoneTypeNum", getPhoneModule());	//设备号
					intentObj.putExtra("longitude", location.getLongitude());	//经度
					intentObj.putExtra("latitude", location.getLatitude());		//纬度
				}else{
					//打开定位弹窗
					showAlertDialog();
				}*/
				
				
				
				//向后台发请求获取门店信息
				//startService(intent);
				
				/*LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
				String locationProvider = null;
				if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
					locationProvider = LocationManager.NETWORK_PROVIDER;
				} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
					locationProvider = LocationManager.GPS_PROVIDER;
				} else {
					Toast.makeText(IndexImageActivity.this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();
				}
				// 获取Location(用来判断是否打开了定位权限)
				Location loc = locationManager.getLastKnownLocation(locationProvider);
				
				//向后台请求门店信息需要用到的参数（里面的经纬度需要定位）
				Intent intent = new Intent(IndexImageActivity.this, IndexService.class);
				Log.i("loc=====", loc.toString());
				
				
				if (loc != null) {//已经打开定位权限，获取定位信息
					intent.putExtra("phoneTypeNum", getPhoneModule());	//设备号
					intent.putExtra("longitude", loc.getLongitude());	//经度
					intent.putExtra("latitude", loc.getLatitude());		//纬度
				} else {//未打开定位权限，出现弹窗提示用户
					showAlertDialog();
				}*/
				
				
/*
			}
		};
		timer.schedule(task, time);*/
	}

	/********* 获取手机型号 ********/
	public String getPhoneModule() {
		String strPhoneModule = android.os.Build.MODEL;
		return strPhoneModule;
	}

	/*** 显示定位弹窗 ****/
	public void showAlertDialog() {
		
		CustomDialog.Builder builder = new CustomDialog.Builder(this);
		builder.setTitle("打开“定位服务”来允许“XX菜店确定您的位置”");

		builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// 转到手机设置界面，用户设置GPS
				dialog.dismiss();
				Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//				startActivity(intent);
				startActivityForResult(intent,1);
			}
		});

		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				Intent intentObj1 = new Intent(IndexImageActivity.this, IndexService.class);
				intentObj1.putExtra("phoneTypeNum", getPhoneModule());
				intentObj1.putExtra("longitude", 0);
				intentObj1.putExtra("latitude", 0);
				Log.i("intent", intentObj1.toString());
				startService(intentObj1);
			}
		});

		// 显示弹窗
		CustomDialog customDialog = builder.create(R.layout.index_popwindow, R.id.title, R.id.set, R.id.cancel, 0, 0);
		customDialog.show();

		// 设置弹窗之外的部分不能点击
		customDialog.setCanceledOnTouchOutside(false);
		/*// 隐藏状态栏
				RelativeLayout rl = (RelativeLayout) findViewById(R.id.pop_window);
				rl.setSystemUiVisibility(View.INVISIBLE);*/
	}

	// 接收广播类
	private String message ;



	public class MessageReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			message = intent.getStringExtra("result");
			Log.e("======", message+"");
			if(isDialog){
				handler.sendEmptyMessage(1);
			}else{
				handler.sendEmptyMessageDelayed(1, 3000);
			}
			context.unregisterReceiver(this);
		}
	}
	/*
	 * 开启gps的情况下返回
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			GPSAppliocation();
		}
	
	/**
	 * 判断是否是第一次登录
	 */
	private boolean isFirstRunandLogin(){
		
		// 是否是第一次运行app(true：第一次；)
		boolean isFirstRun = sharedPreferences.getBoolean("isFirstRunandLogin", true);

		if (isFirstRun) {  //第一次运行APP
			// 改变全局变量的状态
			Editor editor = sharedPreferences.edit();
			editor.putBoolean("isFirstRunandLogin", false);
			editor.commit();
			return false;
		} else {
			// 不是第一次运行，判断用户是否登录(0:未登录)
			int userId = sharedPreferences.getInt("userId", 0);
			if (userId > 0) {// 登录
				// 去首页，显示3秒的门店推广图（上一次的门店图），然后跳转到推广页
				return true;
//				Intent intent = new Intent();
//				intent.setClass(IndexImageActivity.this, IndexActivity.class);
//				startActivity(intent);
			}else{
				return false;
			}
		}
	}
	
	//延迟三秒的操作
	private boolean isDialog=false;
	private String result="error";
	Handler handler=new Handler(){
		 // 子类必须重写此方法,接受数据
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            Log.e("========", "handleMessage......");
            super.handleMessage(msg);
            // 此处可以更新UI
            switch(msg.what){
            case 1:
            	if (!message.equals("error")) {
            		result = message.substring(message.indexOf("\"data\":{"), message.indexOf(",\"code\""));
    				result = result.substring(7);
				}
            	if(!isFirstRunandLogin()){
    				Intent intent2 = new Intent(IndexImageActivity.this, IndexActivity.class);
    				intent2.putExtra("result", result);
    				Editor editor = sharedPreferences.edit();
    				editor.putString("indexResult", result);

					IndexInfo indexInfo = new Gson().fromJson(result, IndexInfo.class);
					int nowStoreId = Integer.parseInt(indexInfo.getStoreId());
					editor.putInt("nowStoreId", nowStoreId);

    				editor.commit();
    				startActivity(intent2);
            	}else{
            		Intent intent = new Intent();
    				intent.setClass(IndexImageActivity.this, SpreadMessage.class);
    				intent.putExtra("result", result);
    				Editor editor = sharedPreferences.edit();
    				editor.putString("indexResult", result);

					IndexInfo indexInfo = new Gson().fromJson(result, IndexInfo.class);
					int nowStoreId = Integer.parseInt(indexInfo.getStoreId());
					editor.putInt("nowStoreId", nowStoreId);

    				editor.commit();
    				startActivity(intent);
            	}
    				finish();
            	break;
            case 2:
            	isDialog=true;
            	showAlertDialog();
            	break;
            }
        }
		
		
	};
	
	/*******************   tools  *****************************/

	//定位
	private void initLoc() {
		//初始化定位
		mLocationClient = new AMapLocationClient(getApplicationContext());
		//设置定位回调监听
		mLocationClient.setLocationListener(this);
		//初始化定位参数
		mLocationOption = new AMapLocationClientOption();
		//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
		mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
		//设置是否返回地址信息（默认返回地址信息）
		mLocationOption.setNeedAddress(true);
		//设置是否只定位一次,默认为false
		mLocationOption.setOnceLocation(true);
		//设置是否强制刷新WIFI，默认为强制刷新
		mLocationOption.setWifiActiveScan(true);
		//设置是否允许模拟位置,默认为false，不允许模拟位置
		mLocationOption.setMockEnable(false);
		//设置定位间隔,单位毫秒,默认为2000ms
		mLocationOption.setInterval(2000);
		//给定位客户端对象设置定位参数
		mLocationClient.setLocationOption(mLocationOption);
		//启 动定位
		mLocationClient.startLocation();
	}

	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		if (amapLocation != null) {
			if (amapLocation.getErrorCode() == 0) {
				//定位成功回调信息，设置相关消息
				amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见官方定位类型表
				latitude = amapLocation.getLatitude();//获取纬度
				longitude = amapLocation.getLongitude();//获取经度
				Log.e("aaa===", "onLocationChanged: "+latitude );
			} else {
				//显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
				Log.e("AmapError", "location Error, ErrCode:"
						+ amapLocation.getErrorCode() + ", errInfo:"
						+ amapLocation.getErrorInfo());

				Toast.makeText(getApplicationContext(), "定位失败", Toast.LENGTH_LONG).show();
			}
		}
	}

	@Override
	public void activate(OnLocationChangedListener listener) {
		mListener = listener;
	}

	@Override
	public void deactivate() {
		mListener = null;
	}
	
}
